<?php

  /*
    注册 后端
  */

  // 1. 接受前端传递来的信息
  $username = $_POST['username'];
  $password = $_POST['password'];
  $nickname = $_POST['nickname'];

  // 2. 验证一下用户名是否存在
  $sql = "SELECT * FROM `users` WHERE `username`='$username'";

  $link = mysqli_connect('localhost', 'root', 'root', 'wyyx');

  $res = mysqli_query($link, $sql);
  $data = mysqli_fetch_all($res, MYSQLI_ASSOC);
  if (count($data)) {
    $arr = [
      "message" => "注册失败, 该用户名已被占用",
      "code" => 2
    ];
    echo json_encode($arr);
    exit;
  }
  $sql2 = "INSERT INTO `users` (`username`, `password`, `nickname`) VALUES('$username', '$password', '$nickname')";
  $res2 = mysqli_query($link, $sql2);
  if ($res2) {
    $arr = [
      "message" => "注册成功,请登录",
      "code" => 1
    ];
  } else {
    $arr = [
      "message" => "注册失败, 请联系管理员",
      "code" => 0
    ];
  }
  echo json_encode($arr);
?>
